package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService loginService;


    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        if (user.getDeptId()!=null){
            List<SysDept> sysDepts = deptService.getChildListByDeptId(user.getDeptId());
            List<Long> sysDeptStrs = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            user.setDeptNode(sysDeptStrs);
        }
        startPage();
        List<SysUser> list = userService.selectAllUserList(user);
        return getDataTable(list);
    }
	
	/**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/userList")
    public TableDataInfo userList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }
    
	/**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/userListSearch")
    public TableDataInfo userListSearch(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.userListSearch(user);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @DeleteMapping("/checkedListSearch/{ids}")
    public List<Map<String,Object>> checkedListSearch(@PathVariable("ids") Long[] ids)
    {
        logger.info("查询选中人员入参：{}",JSON.toJSONString(ids));
        if (ids!=null){
            List<Map<String,Object>> list = userService.checkedListSearch(ids);
            logger.info("查询选中人员出参：{}",list);
            return list;
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/allList")
    public TableDataInfo allList(SysUser user)
    {
        if (user.getDeptId()!=null){
            List<SysDept> sysDepts = deptService.getChildListByDeptId(user.getDeptId());
            List<Long> sysDeptStrs = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            user.setDeptNode(sysDeptStrs);
        }
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user)
    {
        /* if (user.getDeptId()!=null){
            List<SysDept> sysDepts = deptService.getChildListByDeptId(user.getDeptId());
            List<Long> sysDeptStrs = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            user.setDeptNode(sysDeptStrs);
        }
        List<SysUser> list = userService.selectAllUserList(user);*/
        List<SysUser> list = userService.userListSearch(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{id}" })
    public AjaxResult getInfo(@PathVariable(value = "id", required = false) Long id)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(id) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(id))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(id));
            ajax.put("postIds", postService.selectPostListByUserId(id));
            ajax.put("roleIds", roleService.selectRoleListByUserId(id));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        logger.info("添加用户 ,用户入参 ：{}",user.toString());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        logger.info("修改用户 ,用户入参 ：{}",user.toString());
        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 修改手机号码
     */
    @Log(title = "修改手机号码", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePhonenumber")
    public AjaxResult updatePhonenumber(String phonenumber, String code, String uuid)
    {
        return toAjax(loginService.updatePhonenumber(phonenumber, code, uuid));
    }

    /**
     * 重置密码
     */
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 手机号验证码修改密码
     */
    @ApiOperation("手机号验证码修改密码")
    @Log(title = "手机号验证码修改密码", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwdByPhonenumber")
    public AjaxResult editPassword(String phonenumber, String password, String code, String uuid) {
        return toAjax(loginService.editUserPwd(phonenumber, password, code, uuid));
    }
    
    /**
     * 根据用户工号获取用户在各个系统的信息
     */
    //@PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/getUserInfoByJobNoOrPhone")
    public AjaxResult getUserInfoByJobNoOrPhone(SysUser user)
    {
    	if(StringUtils.isNotBlank(user.getUserNo())) {
    		return AjaxResult.success(userService.getUserInfoByJobNoOrPhone(user));
    	}
    	return AjaxResult.error("工号不能为空！");
    }

    
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/getAllUserList")
    public AjaxResult getAllUserList()
    {
        return AjaxResult.success(userService.selectAllUser());
    }

    @GetMapping("/userByUserId")
    public AjaxResult getUserByUserId(String userId){
        return AjaxResult.success(userService.selectUserByUserId(userId));
    }
}
